package com.Test;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.sql.*;

/**
 * Created by Administrator on 2016/4/17.
 */
public class Data {
    private static final String   url  = "jdbc:mysql://127.0.0.1/";
    private static final String driver ="com.mysql.jdbc.Driver";
    private static final String   user = "";
    private static final String   pwd  = "";

    public Connection       conn  = null;
    public  PreparedStatement pst = null;

    public Connection getConn(String table){
        try{
            Class.forName(driver); //获取连接驱动
            conn =DriverManager.getConnection(url+table,user,pwd);//获取连接信息
            if(conn == null){
                System.out.println("data library link error!!! ");
            }
        }catch (ClassNotFoundException e){
            System.out.println(e.getMessage());
        }catch (SQLException e)  {
            System.out.println(e.getMessage());
        }
        return conn;
    }
    /**
     * 关闭数据库连接
     */
    public void close(){

        try{
            pst.close();
            conn.close();
        }catch (SQLException e){
            System.out.println(e.getMessage());
        }
    }

    /**
     * 插入 更新 查询  删除
     * @return
     */
    public  String insertUpdateDelteSelect(String sql,String Type,String Table)throws SQLException{
        Connection conn = this.getConn(Table);
        String flag = "";
        JSONArray array = new JSONArray();
        pst = conn.prepareStatement(sql);
        if(Type.equals("selest")){
            ResultSet rs = pst.executeQuery();
            //获取列数
            ResultSetMetaData rsmd = rs.getMetaData();
            int colCount = rsmd.getColumnCount();
            //遍历输出数据
            while(rs.next()){
                JSONObject jsonObject = new JSONObject();
                //遍历每一列
                for(int i = 1; i <= colCount; i++){
                    String colName = rsmd.getColumnLabel(i);
                    String value = rs.getString(i);
                    jsonObject.put(colName,value);
                }
                array.add(jsonObject);
            }
            flag = array.toString();
        }else if(Type.equals("insert")||Type.equals("delete")||Type.equals("update")) {
            int i = pst.executeUpdate(); //0为未执行 1为成功
            flag = Integer.toString(i);
        }
        System.out.print("result: flag= "+flag+"Type = "+Type);
        this.close();
        return flag;
    }

}
